package com.tmp.alarm.task;

import com.tmp.alarm.utils.MySQLUtils;
import com.tmp.alarm.utils.PropertiesUtil;
import com.tmp.alarm.utils.SendMessagesUtils;
import com.tmp.alarm.utils.UUIDByDateUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 依据job执行进度来判断告警
 */
public class ProgressAlarm {

    private  final  static Logger LOGGER = LoggerFactory.getLogger(ProgressAlarm.class);

    private final   static String processing_type = PropertiesUtil.get("processing_type").trim();
    private  final  static  String final_type = PropertiesUtil.get("final_type").trim();


    /**
     * 根据进度来告警,查询type=2的记录 当   100%>job进度>=大于等于98%时,
     * 没有完成,且持续指定时间内如1h内,可以发出告警,最后将type设置为3
     */
    public static void dealProgressAlarm(){

        String min_progress = PropertiesUtil.get("min_progress").trim();
        String sql = "SELECT m.id,m.type,m.log_time,m.job_id,m.application_progress FROM mart_mobile_job_info AS m " +
                "WHERE m.type="+processing_type+" AND m.application_progress>"+min_progress+" AND m.application_progress<100 GROUP BY job_id";
        try {
            Connection connection =  MySQLUtils.getConnection();
            ResultSet rs = MySQLUtils.query(connection,sql);

            rs.next();
            int rows = rs.getRow();//得到当前行的行号

            String ids = "";
            if(rows >0){
                int limit_progress_time = Integer.parseInt(PropertiesUtil.get("limit_progress_time"));
                rs.beforeFirst();//该方法的作用是将数据库游标移到记录集的最前面，位于记录集第一行的前面，如果记录集不包含任何的行该方法不产生作用
                while (rs.next()){
                    ids = ids+rs.getString("id")+",";
                    String job_id = rs.getString("job_id");
                    String new_log_time = rs.getString("log_time");
                    new_log_time = new_log_time.trim();
                    if(new_log_time.length()<14){
                        new_log_time = new_log_time+"00";
                    }
                    String pro_sql = "SELECT p.id,p.is_alarm,p.log_time FROM progress_alarm p WHERE p.job_id='"+job_id+"' LIMIT 1";
                    ResultSet prs = MySQLUtils.query(connection,pro_sql);

                    prs.next();
                    int prow = prs.getRow();//查询出来只有一条数据,这里就是第一行记录行号为1,以此来判断有没有查询到数据
                    if(prow>0){
                        String is_alarm = prs.getString("is_alarm");
                        if(is_alarm.equals("1")){//表示已经告警过了
                            LOGGER.info("job_id为:"+job_id+" 执行超出设置时间,已经发送消息告警过了,将不再告警...");
                        }else{
                            String old_log_time = prs.getString("log_time");
                            old_log_time = old_log_time.trim();
                            if(old_log_time.length()<14){
                                old_log_time = old_log_time+"00";
                            }
                            boolean timeoutfalg = jdugeProgressTimeOut(new_log_time,old_log_time,limit_progress_time);
                            if(timeoutfalg){//超时,要告警
                                LOGGER.info("job_id为:"+job_id+" 执行超出设置时间,将告警...");
                                //告警的手机号
                                String alarm_list = PropertiesUtil.get("alarm_phone_list").trim();
                                String alarm_title = "job执行超时";
                                String alarm_content = "job_id为:"+job_id+"  的job在规定时间:"+limit_progress_time+"s秒内没有执行完";
                                String messageFlag = SendMessagesUtils.sendMessagesToPhone(alarm_list,alarm_title,alarm_content);
                                if(messageFlag.equals("1")){
                                    //告警成功将会更新progress_alarm中is_alarm为1
                                    String updateSql = "UPDATE progress_alarm SET is_alarm=1 WHERE job_id='"+job_id+"'";
                                    MySQLUtils.executeUpdate(connection,updateSql);
                                    LOGGER.info("进度判断超时告警发送短信成功...");
                                }else{
                                    LOGGER.error("进度判断超时告警发送短信失败!!!");
                                }
                            }else{
                                LOGGER.info("job_id为:"+job_id+"  在progress_alarm中没有超时");
                            }
                        }

                    }else{//在progress_alarm中没有查询到该job,将该job信息存起来
                        String currtimes = UUIDByDateUtils.getCurrentTimes("yyyyMMddHHmmss");
                        String add_sql = "INSERT INTO progress_alarm(job_id,log_time,limit_time,is_alarm,create_time) VALUES('"+job_id+"','"+new_log_time+"','"+limit_progress_time+"',0,'"+currtimes+"')";
                        MySQLUtils.executeUpdate(connection,add_sql);
                    }
                }

                //更新tyep=3
               /* if (StringUtils.isNotEmpty(ids)){
                    ids = "("+ids.substring(0,ids.lastIndexOf(","))+")";
                    String typeSql="UPDATE mart_mobile_job_info SET type=3 WHERE id IN "+ids;
                    LOGGER.info("将要更新type对应sql为:"+typeSql);
                    MySQLUtils.executeUpdate(connection,typeSql);
                }*/
            }else{
                LOGGER.info("进度告警没有查到数据sql为:"+sql);
            }
            MySQLUtils.returnConnection(connection);

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("查询进度判断告警异常...");
            throw new RuntimeException("查询进度判断告警异常..."+e.getMessage());
        }
    }


    /**
     *
     * @param new_log_time  每次查询mart_mobile_job_info获取
     * @param old_log_time  根据job_id查询progress_alarm获取
     * @param limit_time  限制时间段
     * @return  超时返回true 没超时返回false
     */
    public static  boolean  jdugeProgressTimeOut(String new_log_time,String old_log_time,int limit_time){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        boolean flag = false;//默认开始没有超时
        try {
            Date new_date = sdf.parse(new_log_time.trim());
            long new_time = new_date.getTime();

            Date old_date = sdf.parse(old_log_time.trim());
            long old_time = old_date.getTime();

            long exe_time = (new_time-old_time)/1000;
            if(exe_time>limit_time){//超时
                flag = true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("解析判断进度log_time异常:"+e.getMessage());
        }
        return flag;
    }

}
